package com.bigtotoro.shuiyincamera.image;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.MyArtListActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.editimage.EditImageActivity;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.util.FileUtils;
import com.umeng.analytics.MobclickAgent;


import java.io.File;


/**
 * 图片添加水印
 */
public class AddWaterMarkActivity extends BaseActivity implements View.OnClickListener {
    public static final int REQUEST_PERMISSON_SORAGE = 1;
    public static final int REQUEST_PERMISSON_CAMERA = 2;

    public static final int SELECT_GALLERY_IMAGE_CODE = 7;
    public static final int TAKE_PHOTO_CODE = 8;
    public static final int ACTION_REQUEST_EDITIMAGE = 9;
    public static final int ACTION_STICKERS_IMAGE = 10;
    private AddWaterMarkActivity context;
    private ImageView imgView;
    private TextView btn_check_through;
    private Bitmap mainBitmap;
    private int imageWidth, imageHeight;//
    private String path;

    private Uri photoURI = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_water_mark);
        initBase();
        initView();

    }

    private void initView() {
        context = this;
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels;
        imageHeight = metrics.heightPixels;
        imgView = (ImageView) findViewById(R.id.img);
        btn_check_through = findViewById(R.id.btn_check_through);//查看我的作品
        btn_check_through.setOnClickListener(this);

        path = getIntent().getStringExtra("path");
        startLoadTask();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_check_through:   //查看我的作品
                startActivity(new Intent(AddWaterMarkActivity.this, MyArtListActivity.class));
                break;
        }
    }

    /**
     * 编辑图片
     */
    private void editImageClick() {
        File outputFile = FileUtils.genEditFile();

        //EditImageActivity的结构决定了大部分功能都可以在editimageActivity中完成，
        //控制画布显示隐藏和保存图片等交互性操作放在各个fragment中
        //拆掉底部的viewpager，每个界面单独写一个底部操作菜单，甚至可以完全脱离EditImageActivity
        //在每个activity中单独放置底部画布和交互画布
        EditImageActivity.start(this, path, outputFile.getAbsolutePath(),
                ACTION_REQUEST_EDITIMAGE,"加水印");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTION_REQUEST_EDITIMAGE){
            switch (resultCode){
                case RESULT_OK://从编辑界面返回
                    handleEditorImage(data);
                    break;
                case RESULT_CANCELED:
                    finish();
                    break;
            }
        }
    }

    private void handleEditorImage(Intent data) {
        String newFilePath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT);
        boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false);

        if (isImageEdit) {  //如果编辑完成
//            Toast.makeText(this, getString(R.string.save_path, newFilePath), Toast.LENGTH_LONG).show();

            //放入图片列表
            MyArt art = new MyArt();
            art.setHeight(imageHeight);
            art.setWidth(imageWidth);
            art.setCreate_time(System.currentTimeMillis()+"");
            art.setPath(newFilePath);
            art.setType(0);
            art.save();
        } else {    //如果未编辑  还是用原来的图片
            finish();
            newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH);
        }
        //System.out.println("newFilePath---->" + newFilePath);
        //File file = new File(newFilePath);
        //System.out.println("newFilePath size ---->" + (file.length() / 1024)+"KB");
        Log.d("image is edit", isImageEdit + "");
        LoadImageTask loadTask = new LoadImageTask();
        loadTask.execute(newFilePath);  //异步载入图片



    }

    private void startLoadTask() {
        LoadImageTask task = new LoadImageTask();
        task.execute(path);
        editImageClick();
    }

    /**
     * 这个方法是为了获取图片的，异步获取图片方法
     */
    private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {
            return BitmapUtils.getSampledBitmap(params[0],
                    imageWidth / 4, imageHeight / 4);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (mainBitmap != null) {
                mainBitmap.recycle();
                mainBitmap = null;
                System.gc();
            }
            mainBitmap = result;
            imgView.setImageBitmap(mainBitmap);  //mainActivity中三个按钮上方的图片框

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("AddWaterMarkActivity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("AddWaterMarkActivity");//统计页面
        MobclickAgent.onPause(this);
    }
}
